<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      [v-cloak] {
        display: none;
      }
    </style>
  </head>
  <body>
    <!-- 
      网页授权机制

          基本信息：
              1. 当前网页访问地址
                https://will.natapp4.cc/user.html
              2. 将该地址做 encode 操作
                https%3A%2F%2Fwill.natapp4.cc%2Fuser.html
              3. 将 encode 之后地址，组装授权地址
                https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9551c38135f5192e&redirect_uri=https%3A%2F%2Fwill.natapp4.cc%2Fuser.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

        1. 用户访问组装之后的授权地址，会弹出授权确认框，同意之后，将重定向到 
            https://will.natapp4.cc/user.html?code=xxxxx&state=STATE
        
        2. 获取 url 地址上的 code 参数，去换取 access_token
     -->

    <div id="app" v-cloak>
      <h1>验证网页授权机制</h1>

      <div v-if="userInfo">
        <img :src="userInfo.headimgurl" alt="" />
        <p>昵称：{{userInfo.nickname}}</p>
      </div>
    </div>

    <!-- 引入 Vue SDK -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
      Vue.createApp({
        data() {
          return {
            userInfo: null,
          };
        },

        async mounted() {
          // 获取 code 参数
          const code = new URL(window.location.href).searchParams.get("code");
          console.log("code", code);

          // 调用后端 login 接口
          const resp = await fetch(`/api/login?code=${code}`).then((response) =>
            response.json()
          );

          // 修改 userInfo
          this.userInfo = resp;

          console.log("resp", resp);
        },
      }).mount("#app");
    </script>
  </body>
</html>
